<?php

namespace app\api\controller;

use app\api\BaseController;
use app\api\middleware\Auth;
use app\common\controller\WxPay;
use think\facade\Db;

class User extends BaseController
{
    protected $middleware = [
        Auth::class => ['except' => [''] ]
    ];

    /**
     * 账号注销
     */
    public function userXiao()
    {
        $param = get_params();
        if (empty($param['code'])) {
            return error('短信验证码不能为空');
        }
        //验证码校验
        $mobile = Db::name('user')->where('id',JWT_UID)->value('mobile');
        $code = cache('register_code_'.$mobile);
        if ($code != $param['code']) {
            return json(['code'=>1,'msg'=>'验证码错误']);
        }
        cache('register_code_'.$mobile,null);
        $user_info = Db::name('user')->where(['id'=>JWT_UID])->find();
        if (empty($user_info)) {
            return error('您的账户已注销成功,请刷新后重试');
        }
        Db::name('user_xiao')->insert([
            'uid' => $user_info['id'],
            'user_info' => json_encode($user_info,JSON_UNESCAPED_UNICODE),
            'create_time' => time()
        ]);
        Db::name('user')->where(['id'=>JWT_UID])->delete();
        return success('注销成功');
    }

    /**
     * 导出统计
     */
    public function stat()
    {
        $data['one_hai'] = Db::name('hai')->where(['type'=>1,'news_type'=>1,'uid'=>JWT_UID])->count();
        $data['one_zhan'] = Db::name('hai')->where(['type'=>2,'news_type'=>1,'uid'=>JWT_UID])->count();
        $data['one_dao'] = Db::name('news_dao')->alias('d')
                    ->join('news n','d.news_id=n.id')
                    ->where([['d.uid','=',JWT_UID],['n.news_file_id','=',0]])
                    ->group('d.news_id')
                    ->count();
        $data['one_ci'] = Db::name('news_dao')->alias('d')
                    ->join('news n','d.news_id=n.id')
                    ->where([['d.uid','=',JWT_UID],['n.news_file_id','=',0]])
                    ->count();
        $data['two_hai'] = Db::name('hai')->where(['type'=>1,'news_type'=>2,'uid'=>JWT_UID])->count();
        $data['two_zhan'] = Db::name('hai')->where(['type'=>2,'news_type'=>2,'uid'=>JWT_UID])->count();
        $data['two_dao'] = Db::name('news_dao')->alias('d')
                    ->join('news n','d.news_id=n.id')
                    ->where([['d.uid','=',JWT_UID],['n.news_file_id','>',0]])
                    ->group('d.news_id')
                    ->count();
        $data['two_ci'] = Db::name('news_dao')->alias('d')
                ->join('news n','d.news_id=n.id')
                ->where([['d.uid','=',JWT_UID],['n.news_file_id','>',0]])
                ->count();
        return success('',$data);
    }

    /**
     * 开通会员
     */
    public function vipPay()
    {
        $param = get_params();
        $level = Db::name('user_level')->where('id',$param['id'])->find();
        $insert = [
            'uid' => JWT_UID,
            'order_no' => date('YmdHis').rand(1000,9999),
            'amount' => $level['money'],
            'pay_type' => $param['pay_type'],
            'level' => $param['id'],
            'goods_info' => json_encode($level,JSON_UNESCAPED_UNICODE),
            'create_time' => time()
        ];
        Db::name('user_level_log')->insert($insert);
        $wx = new WxPay();
        if ($insert['pay_type'] == 1) {
            //微信支付
            $notify_url = request()->domain()."/api/notify/memberPayResult";
            $res = $wx->appPay($insert['order_no'],$notify_url,$insert['amount']);
            return json($res);
        } else {
            //支付宝
            $notify_url = request()->domain().'/api/notify/aliNotify';
            $result = $wx->alipays($insert,$notify_url);
            return json(['code'=>0,'msg'=>'success','data'=>$result]);
        }
    }

    /**
     * 会员中心
     */
    public function vipConfig()
    {
        $user = Db::name('user')->where('id',JWT_UID)->find();
        if (!empty($user['vip_end_time_one'])) {
            $user['vip_end_time_one'] = date('Y-m-d',$user['vip_end_time_one']);
        }
        if (!empty($user['vip_end_time_two'])) {
            $user['vip_end_time_two'] = date('Y-m-d',$user['vip_end_time_two']);
        }
        if (!empty($user['svip_end_time_one'])) {
            $user['svip_end_time_one'] = date('Y-m-d',$user['svip_end_time_one']);
        }
        if (!empty($user['svip_end_time_two'])) {
            $user['svip_end_time_two'] = date('Y-m-d',$user['svip_end_time_two']);
        }
        $user_level = Db::name('user_level')->order('id asc')->select()->toArray();
        
        $return = [
            'user' => $user,
            'user_level' => $user_level,
        ];
        return success('',$return);
    }

    /**
     * 我的订单
     */
    public function order()
    {
        $param = get_params();
        $sql[] = ['uid','=',JWT_UID];
        $sql[] = ['delete_time','=',0];
        $sql[] = ['order_type','=',1];
        $sql[] = ['status','=',$param['status']];
        $data = Db::name('order')->where($sql)
                    ->order('id desc')
                    ->page($param['page'])
                    ->limit(10)
                    ->select()
                    ->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $val['pay_time'] = datetime($val['pay_time']);
            }
        }
        return success('',$data);
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $param = get_params();
        $data = Db::name('order')->where('id',$param['id'])->find();
        $data['device'] = Db::name('device')->where('id',$data['device_id'])->find();
        $data['address'] = json_decode($data['address'],true);
        if (!empty($data['recharge_info'])) {
            $data['recharge_info'] = json_decode($data['recharge_info'],true);
        }
        $data['create_time'] = datetime($data['create_time']);
        $data['pay_time'] = datetime($data['pay_time']);
        if (!empty($data['sh_img'])) {
            $data['sh_img'] = explode(',',$data['sh_img']);
        } else {
            $data['sh_img'] = [];
        }
        if (!empty($data['update_time'])) {
            $data['update_time'] = datetime($data['update_time']);
        }
        if (!empty($data['sh_time'])) {
            $data['sh_time'] = datetime($data['sh_time']);
        }
        return success('',$data);
    }

    /**
     * 取消申诉
     */
    public function cancelOrder()
    {
        $param = get_params();
        $data = Db::name('order')->where('id',$param['id'])->find();
        if ($data['sh_status'] == 4) {
            return success('已取消申诉');
        }
        Db::name('order')->where('id',$param['id'])->update([
            'status' => 3,
            'sh_status' => 4,
            'cancel_time' => time(),
        ]);
        return success('已取消申诉');
    }

    /**
     * 我的兑酒券
     */
    public function couponList()
    {
        $param = get_params();
        $sql[] = ['uid','=',JWT_UID];
        $sql[] = ['user_type','=',1];
        $sql[] = ['delete_time','=',0];
        $sql[] = ['status','=',$param['status']];
        $data = Db::name('coupon_log')->where($sql)
                    ->order('id desc')
                    ->page($param['page'])
                    ->limit(10)
                    ->select()
                    ->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $val['end_time'] = date('Y-m-d',$val['end_time']);
            }
        }
        return success('',$data);
    }

    /**
     * 兑酒类型
     */
    public function cate()
    {
        $data = Db::name('cate')->field('id,title')->where(['delete_time'=>0])->order('sort desc')->select();
        return success('',$data);
    }

    /**
     * 会员等级
     */
    public function userLevel()
    {
        $data = Db::name('user_level')->where(['delete_time'=>0])->order('id asc')->select()->toArray();
        if (empty($data)) {
            return success('');
        }
        $user = Db::name('user')->where('id',JWT_UID)->find();
        foreach ($data as &$val) {
            if ($user['level'] < $val['id']) {
                $val['status'] = 0; //未超越
            } elseif ($user['level'] == $val['id']) {
                $val['status'] = 1; //当前
            } else {
                $val['status'] = 2; //已超越
            }
        }
        $config = Db::name('config')->where('id',10)->find();
        $conf = unserialize($config['content']);
        $return = [
            'explain' => $conf['rule_desc'],
            'list' => $data
        ];
        return success('',$return);
    }

    /**
     * 立即兑换
     */
    public function toDui()
    {
        $param = get_params();
        if (empty($param['device_id'])) {
            return error('请选择设备');
        }
        $couponLog = Db::name('coupon_log')->where('id',$param['coupon_id'])->find();
        if ($couponLog['status'] != 1) {
            return error('当前兑酒券已使用');
        }
        $start_time = strtotime(date('Y-m-d 00:00:00'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));
        //今天是否使用兑酒券
        $order_info = Db::name('order')
            ->where([['uid','=',JWT_UID],['pay_type','=',3],['status','>',0],['create_time','between',[$start_time,$end_time]]])
            ->find();
        if (!empty($order_info)) {
            return error('兑酒券每天限用1张');
        }
        $device = Db::name('device')->alias('d')
                    ->join('cate c','d.cate_id=c.id')
                    ->field('d.*,c.title as cate_name')
                    ->where('d.id',$param['device_id'])
                    ->find();
        if (empty($device)) {
            return error('未找到设备信息');
        }
        if ($device['status'] != 'run') {
            return error('设备故障');
        }
        if ($device['weight'] < $couponLog['nums']) {
            return error('当前设备酒量不足');
        }
        $shop = Db::name('user_one')->field('id,user_name,mobile,address')
            ->where('id',$device['user_one'])->find();
        $insert = [
            'uid' => JWT_UID,
            'coupon_id' => $param['coupon_id'],
            'device_id' => $param['device_id'],
            'wine_num' => $couponLog['nums'],
            'wine_name' => $device['cate_name'],
            'order_no' => date('YmdHis').rand(1000,9999),
            'out_found_no' => 'BK'.date('YmdHis').rand(100,999),
            'address' => json_encode($shop,JSON_UNESCAPED_UNICODE),
            'status' => 1,
            'pay_status' => 1,
            'pay_type' => 3,
            'create_time' => time(),
            'pay_time' => time(),
        ];
        //服务器下发订单预创建信息
        $work = new Work();
        $topic = 'liquor/s/'.$device['imei'].'/order';
        //服务器下发订单创建信息
        $msg = json_encode([
            "orderNum" => $insert['order_no'],
            "weight" => $insert['wine_num'],
            "msgId" => $device['msgId'],
            "type"  => "create"
        ]);
        $work->preOrder($topic,$msg);
        $orderId = Db::name('order')->insertGetId($insert);
        Db::name('coupon_log')->where('id',$param['coupon_id'])->update(['status'=>2,'update_time'=>time()]);
        //服务器下发订单支付成功信息
        $msg = json_encode([
            "orderNum" => $insert['order_no'],
            "weight" => $insert['wine_num'],
            "msgId" => $device['msgId'],
            "type"  => "pay"
        ]);
        $work->preOrder($topic,$msg);
        return json(['code'=>0,'msg'=>'支付成功','data'=>['order_id'=>$orderId]]);
    }

    /**
     * 意见反馈
     */
    public function feedback()
    {
        if (request()->isPost()) {
            $param = request()->param();
            if (empty($param['content'])) {
                return error('反馈内容为空');
            }
            $add = [
                'uid' => JWT_UID,
                'content' => $param['content'],
                'create_time' => time()
            ];
            if (!empty($param['img'])) {
                $add['img'] = $param['img'];
            }
            if (!empty($param['mobile'])) {
                $add['mobile'] = $param['mobile'];
            }
            Db::name('feedback')->insert($add);
            return success('提交成功');
        }
    }

    /**
     * 积分明细
     */
    public function scoreLog()
    {
        $param = get_params();
        $data = Db::name('score_log')->where(['uid'=>JWT_UID,'delete_time'=>0])
                    ->order('id desc')
                    ->page($param['page'])
                    ->limit(10)
                    ->select()
                    ->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $val['create_time'] = datetime($val['create_time']);
            }
        }
        return success('',$data);
    }
}